package com.gzhryc.weixin.xcx;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.secruity.AESTools;
import com.gzhryc.weixin.xcx.dto.Jscode2SessionResponse;
import com.gzhryc.weixin.xcx.dto.XcxEncryptedData;
import com.gzhryc.weixin.xcx.exceptions.XcxErrorException;

public class XcxAuthorityApi {
	
	private final String appid;
	private final String secret;
	
	public XcxAuthorityApi(String appid,String secret){
		this.appid = appid;
		this.secret = secret;
	}

	public String getAppid() {
		return appid;
	}
	
	public String getSecret() {
		return secret;
	}

	/**
	 * 获取Oauth2的AccessToken
	 * @param code	用户授权Code
	 * @return
	 * @throws XcxErrorException 
	 */
	public Jscode2SessionResponse jscode2Session(String code) throws XcxErrorException, URISyntaxException, IOException {
		CloseableHttpResponse response = null;
		try {
			CloseableHttpClient httpclient = HttpClients.createDefault();
			URI uri = new URIBuilder()
		        .setScheme("https")
		        .setHost("api.weixin.qq.com")
		        .setPath("/sns/jscode2session")
		        .setParameter("appid",appid)
		        .setParameter("secret",secret)
		        .setParameter("js_code",code)
		        .setParameter("grant_type","authorization_code")
		        .build();
			HttpGet httpget = new HttpGet(uri);
			response = httpclient.execute(httpget);
			HttpEntity entity = response.getEntity();
			if(entity != null){
				String str = EntityUtils.toString(entity,Charset.forName("UTF-8"));
				if(XcxErrorException.isErrorResponse(str)){
					throw new XcxErrorException(JsonTools.fromJson(str, XcxErrorException.ErrorResponse.class));
				}else{
					return JsonTools.fromJson(str, Jscode2SessionResponse.class);
				}
			}
		} catch(Exception e){
			throw e;
		} finally {
			if(response != null){
				try {
					response.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return null;
	}
	
	/**
	 * 小程序的用户信息解密
	 * @param encryptedData
	 * @param sessionKey
	 * @param iv
	 * @return
	 */
	public static XcxEncryptedData decrypt(String encryptedData,String sessionKey,String iv){
		try {
			byte[] resultByte  = AESTools.get().decrypt(Base64.decodeBase64(encryptedData),  
			        Base64.decodeBase64(sessionKey),
			        Base64.decodeBase64(iv));
			
			if(null != resultByte && resultByte.length > 0){  
                String userInfo = new String(resultByte, "UTF-8");                 
                return JsonTools.fromJson(userInfo, XcxEncryptedData.class);
            }
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} 
		return null;
	}
}
